package com.atguigu.gmall.user.controller;


import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {

    @Autowired
    private UserService userService;
    @Autowired
    public RedisTemplate redisTemplate;

    //提交登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){

        //1:判断用户名和密码不能为 NULL 或  “”   “      ”
        //影响编译期  Java class  不影响运行期


        //2:登录成功  返回值
        UserInfo userInfo1 =  userService.login(userInfo);

        if (null != userInfo1){
            Map map = new HashMap<>();
            //token  UUID 36位长度的字符串  去掉4个小横线  32长度字符串
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            map.put("token",uuid);
            //昵称
            map.put("nickName",userInfo1.getNickName());
            //缓存
            redisTemplate.opsForValue().set(uuid,userInfo1.getId().toString(),
                    RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);

        }else {
            //登录失败
            return Result.fail().message("用户名或密码不正确！");
        }

    }
}
